package com.longsys.eventsourcing.demo.controller;

import com.longsys.eventsourcing.core.EventUser;
import com.longsys.eventsourcing.demo.eventsourcing.domain.RoleAggr;
import com.longsys.eventsourcing.demo.eventsourcing.domain.UserAggr;
import com.longsys.eventsourcing.demo.eventsourcing.event.RoleCreatedEvent;
import com.longsys.eventsourcing.demo.eventsourcing.event.UserCreatedEvent;
import com.longsys.eventsourcing.demo.mapper.RoleMapper;
import com.longsys.eventsourcing.demo.mapper.UserMapper;
import com.longsys.eventsourcing.demo.model.Role;
import com.longsys.eventsourcing.demo.model.User;
import com.longsys.eventsourcing.demo.model.UserRole;
import com.longsys.framework.eventsourcing.sbclient.core.EventStoreClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author guozhu.huang
 * @date 2021/9/19 14:43
 */
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private EventStoreClient eventStoreClient;

    @PostMapping("/addUser")
    public String addUser(@RequestBody User user) {
        userMapper.insert(user);

        eventStoreClient.store(UserCreatedEvent.class, UserAggr.class, user.getId(),
                new EventUser("id", "name"));

        return "ok";
    }

    @PostMapping("/addRole")
    public String addUserRole(@RequestBody Role role) {
        roleMapper.insert(role);

        eventStoreClient.store(RoleCreatedEvent.class, RoleAggr.class, role.getRoleId(),
                new EventUser("id", "name"));

        return "ok";
    }
}
